package com.write.program.db.dao;


import com.write.program.db.meta.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Endstart
 * Date: 2020-05-03
 * Time: 18:11
 */
public class UserDao {

    private static UserDao instance = new UserDao();

    public static UserDao getInstance() {
        return instance;
    }

    private UserDao() { }

    public boolean insert(User user) {
        String sql = "Insert into User(username,password) value (?,?)";
        try (PreparedStatement pst = DaoUtil.getConnect().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pst.setString(1, user.getUsername());
            pst.setString(2, user.getPassword());
            if (pst.executeUpdate() > 0) {
                ResultSet rs = pst.getGeneratedKeys();
                rs.next();
                user.setId(rs.getInt(1));
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public User getByUsername(String username) {
        String sql = "Select * from User where username = ?";
        try (PreparedStatement pst = DaoUtil.getConnect().prepareStatement(sql)) {
            pst.setString(1, username);
            ResultSet resultSet = pst.executeQuery();
            if (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<User> getAll() {
        String sql = "select * from User";
        try {
            Connection con = DaoUtil.getConnect();
            PreparedStatement pst = con.prepareStatement(sql);
            ResultSet resultSet = pst.executeQuery();
            return parseRet(resultSet);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<User> parseRet(ResultSet resultSet) throws SQLException {
        List<User> list = new ArrayList<>();
        while (resultSet.next()) {
            User client = new User();
            client.setId(resultSet.getLong("id"));
            client.setUsername(resultSet.getString("username"));
            client.setPassword(resultSet.getString("password"));
            list.add(client);
        }
        return list;
    }



}
